package com.lms.collection.queue;

import lombok.Data;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-22 07:06
 * @Description:
 */
public class DelayQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Item> delayeds = new DelayQueue<>();

        delayeds.put(new Item("item1", 5, TimeUnit.SECONDS));
        delayeds.put(new Item("item2", 10, TimeUnit.SECONDS));
        delayeds.put(new Item("item3", 15, TimeUnit.SECONDS));
        System.out.println("begin time:" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        for (int i = 0; i < 3; i++) {
            Item take = delayeds.take();
            System.out.format("name:{%s},time:{%s}\n", take.getName(), LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }
        delayeds.put(new Item("item1", 5, TimeUnit.SECONDS));
        delayeds.put(new Item("item2", 10, TimeUnit.SECONDS));
        delayeds.put(new Item("item3", 15, TimeUnit.SECONDS));
        System.out.println("-----------");
        for (Item item : delayeds) {
            System.out.format("name:{%s},time:{%s}\n", item.getName(), LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        }

    }
}


@Data
class Item implements Delayed {
    private long time;
    private String name;

    public Item(String name, long time, TimeUnit unit) {
        this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0);
        this.name = name;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return time - System.currentTimeMillis();
    }

    @Override
    public int compareTo(Delayed o) {
        Item item = (Item) o;
        long diff = this.time - item.time;
        if (diff <= 0) {
            return -1;
        } else {
            return 1;
        }
    }
}